package com.manolovn.trianglify.renderer;

import com.manolovn.trianglify.domain.Triangle;
import com.manolovn.trianglify.generator.color.ColorGenerator;
import com.manolovn.trianglify.generator.color.RandomColorGenerator;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.utils.Color;

import java.util.Collection;

/**
 * Triangle renderer
 */
public class TriangleRenderer {
    private Paint trianglePaint;
    private ColorGenerator colorGenerator;
    private Path path;

    public TriangleRenderer(ColorGenerator colorGenerator) {
        this.colorGenerator = colorGenerator;
        initPaint();
    }

    private void initPaint() {
        trianglePaint = new Paint();
        trianglePaint.setStyle(Paint.Style.FILL_STYLE);
        trianglePaint.setAntiAlias(true);
        trianglePaint.setStrokeWidth(2);
        trianglePaint.setStrokeCap(Paint.StrokeCap.SQUARE_CAP);
        trianglePaint.setStrokeJoin(Paint.Join.BEVEL_JOIN);

        if (colorGenerator == null) {
            colorGenerator = new RandomColorGenerator();
        }

        path = new Path();
        path.setFillType(Path.FillType.EVEN_ODD);
    }

    /**
     * this method is used to draw triangles on canvas
     *
     * @param triangles number of triangles need to be render
     * @param canvas it will paint all triangles on screen
     */
    public void render(Collection<Triangle> triangles, Canvas canvas) {
        colorGenerator.setCount(triangles.size());
        for (Triangle triangle : triangles) {
            path.reset();

            path.moveTo(triangle.a.x, triangle.a.y);
            path.lineTo(triangle.b.x, triangle.b.y);
            path.lineTo(triangle.c.x, triangle.c.y);
            path.lineTo(triangle.a.x, triangle.a.y);
            path.close();

            int color = colorGenerator.nextColor();

            trianglePaint.setColor(new Color(color));
            canvas.drawPath(path, trianglePaint);
        }
    }
}
